<?php


namespace App\Http\Controllers\Admin;


use App\Models\Agency;
use App\Models\AgencyDevice;
use App\Models\Device;
use App\Models\History;
use App\Models\Kind;
use App\Models\Type;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

/**
 * 设备管理
 * Class deviceController
 * @package App\Http\Controllers\Admin
 */
class DeviceController extends BaseController
{
    /**
     * 按照平台和学校区分不同，展示不同范围的数据，
     * 显示形式相同。
     *
     * 平台展示所有
     * 学校展示本校设备
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        $admin = $this->getAdmin();
        $query = $request->only(['code', 'kind_id', 'agency_id']);
        $isSchool = $this->isSchool();

        if($isSchool){
            $query['agency_id'] = $admin->agency->id;
        }
        $where = Device::selectQuery($query);
        $list = Device::where($where)->orderBy("id", "desc")->paginate(config('site.other.paginate'));
        $list = $list->appends($query);

        $agencies = Agency::all();
        $kinds = Kind::all();

        return backendView('device.index', compact('list', 'query', 'agencies', 'kinds', 'isSchool'));
    }

    /**
     * 新增设备
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function add(Request $request)
    {
        if ($request->isMethod('post')) {

            $this->validate($request, [
                'codes' => 'required|max:255',
                'kind_id' => 'required|exists:kinds,id'
            ], [], [
                'codes' => __("Code"),
                'kind_id' => '设备类型'
            ]);

            $data = $request->only(['codes', 'kind_id']);

            $request = Device::add($data);
            if ($request) {
                return redirect()->route('admin.device.index')->with('success', __('Create success'));
            }

            return back()->with('error', __('Create failed'))->withInput();
        } else {
            $kinds = Kind::where('status', 1)->get();
            //dd($type);
            return backendView('device.add', compact('kinds'));
        }
    }

    /**
     * 编辑分类
     * @param Request $request
     * @param null $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function edit(Request $request, $id = null)
    {
        /**
         * @var $device Device
         */
        $device = Device::find($id);
        if (empty($device)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }

        if ($request->isMethod('POST')) {

            $this->validate($request, [
                'code' => 'required|max:255',
                'agency_id' => 'sometimes|exists:agencies,id',
                'kind_id' => 'required|exists:kinds,id'
            ], [], [
                'code' => __("Code"),
                'agency_id' => '机构名',
                'kind_id' => '设备类型'
            ]);

            $data = $request->only(['code', 'kind_id', 'agency_id']);

            if ($device->update($data)) {
                return redirect()->route('admin.device.index')->with('success', __('Edit success'));
            }

            return back()->with('error', __('Edit failed'))->withInput();

        } else {
            $kinds = Kind::where('status', 1)->get();
            $agencies = Agency::all();

            return backendView('device.edit', compact('device', 'kinds', 'agencies'));
        }
    }

    /**
     * 查看分类
     * @param null $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function view($id = null)
    {
        /**
         * @var $device Device
         */
        $device = Device::find($id);
        if (empty($device)) {
            return back()->with('error', __('The page you requested was not found'));
        }
        $isSchool = $this->isSchool();
        return backendView('device.view', compact('device','isSchool'));
    }

    /**
     * 删除分类
     * @param null $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function delete($id = null)
    {
        /**
         * @var $device Device
         */
        $device = Device::find($id);
        if (empty($device)) {
            return back()->with('error', __('The page you requested was not found'));
        }

        try {

            $users = $device->users()->get();
            $devices = $device->deviceDevices()->get();

            if (count($users) > 0 || count($devices) > 0) {
                return back()->with('error', '机构下有账户或设备，不能删除');
            }

            if ($device->delete()) {
                return back()->with('success', __('Delete success'));
            }
        } catch (\Exception $e) {
            Log::error('device delete error:');
            Log::error($e->getMessage());
        }

        return back()->with('error', __('Delete failed'));
    }

}